#!/bin/bash

# 被比较的文件名,公司电脑就写.ideavimrcCompany，自己电脑就写.ideavimrc

file_name="baseCompany.yml"
# file_name="base.yml"
user_name="pc"
# 定义日志文件的路径
# 获取Windows用户名
IDEAVIMRCPATH="/mnt/c/Users/$user_name"
# 日志路径
LOGFILE="$IDEAVIMRCPATH/ideavim-auto-commit/espansoScript.log"


# 启动日志记录
echo "Starting script at $(date)" > "$LOGFILE"

# 切换到 Git 仓库目录
cd "$IDEAVIMRCPATH/ideavim-auto-commit" || {
    echo "Failed to change directory to the repository" >> "$LOGFILE"
    exit 1
}

# 确保 git 命令可用
PATH="$PATH:/usr/bin/git"

# 检查 .ideavimrc 文件是否存在
if [ ! -e "/mnt/c/Users/$user_name/AppData/Roaming/espanso/match/base.yml" ]; then
    echo "base.yml file does not exist" >> "$LOGFILE"
    exit 1
fi

# 检查 .ideavimrc 文件内容是否有变化
if ! cmp -s "/mnt/c/Users/$user_name/AppData/Roaming/espanso/match/base.yml" "$file_name"; then
    # 只有在文件不同时才复制
    echo "Updating base.yml in the repository..." >> "$LOGFILE"
    cp -f "/mnt/c/Users/$user_name/AppData/Roaming/espanso/match/base.yml" "$file_name" >> "$LOGFILE" 2>&1 || {
        echo "Failed to copy base.yml file" >> "$LOGFILE"
        exit 1
    }

    # 添加所有修改和新文件
    git add -A >> "$LOGFILE" 2>&1 || {
        echo "Failed to add files" >> "$LOGFILE"
        exit 1
    }

    # 提交变更
    git commit -m "Scheduled commit" >> "$LOGFILE" 2>&1 || {
        echo "Failed to commit changes" >> "$LOGFILE"
        exit 1
    }

    # 推送到远程仓库
    git push >> "$LOGFILE" 2>&1 || {
        echo "Failed to push changes" >> "$LOGFILE"
        exit 1
    }
else
    echo "No changes in base.yml to update" >> "$LOGFILE"
fi

# 记录脚本结束时间
echo "Script ended at $(date)" >> "$LOGFILE"
